<template>
  <section>
    <el-row>
      <el-col :span="24">
        <!--顶部操作按钮-->
        <el-space class="top-btns">
          <el-dropdown split-button type="primary" size="small" @click="loadData(true, true)">导出
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-button type="primary" size="small" @click="loadData(true)">勾选导出</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="info" size="small" @click="handleEdit({})">添加</el-button>
          <el-dropdown type="primary" size="small">
            <el-button type="info" size="small">批量操作
              <el-icon class="el-icon--right">
                <arrow-down/>
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-button type="info" size="small" @click="onpenStatusBatchEdit">激活</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="success" size="small" @click="onSubmit">刷新</el-button>
        </el-space>

        <!--搜索表单-->
        <el-form :inline="true" size="small">
          <el-form-item label="登录账户">
            <el-input v-model="criteria.username" placeholder="登录账户"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button type="primary" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
        <!--数据表格-->
        <el-table :data="tableData" border size="small" @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" width="40"/>
          <el-table-column prop="username" label="登录账户" align="center"></el-table-column>
          <el-table-column prop="nickname" label="昵称" align="center"></el-table-column>
          <el-table-column label="角色" #default="scope" align="center">
            <el-tag style="margin-right:5px" v-for="(v,i) in scope.row.authTitle" :key="i">{{ v.title }}</el-tag>
          </el-table-column>
          <el-table-column prop="login_num" label="登录次数" align="center"></el-table-column>
          <el-table-column label="状态" align="center">
            <template #default="scope">
              <el-switch :model-value="scope.row.status ? true : false"
                         @change="changeStatus($event, scope.$index, scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="create_at" label="添加时间" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" @click="handleEdit(scope.row)" size="small"><el-icon><EditPen/></el-icon></el-button>
              <el-button type="danger" @click="handleDelete(scope.row)" size="small"><el-icon><Delete/></el-icon></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination background @current-change="handleCurrentChange" @size-change="handleSizeChange"
                         :current-page="page" :page-size="pageSize"
                         :page-sizes="[20, 50, 100, 200, 1000]"
                         layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="dialogTitle" center v-model="dialogFormVisible">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="登录账户" prop="username">
          <el-input v-model="form.username" :disabled="!!form.id"></el-input>
        </el-form-item>
        <el-form-item label="账户昵称" prop="nickname">
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="角色权限" prop="auth_ids">
          <el-checkbox-group v-model="form.auth_ids">
            <el-checkbox v-for="(v,index) in authList" :label="String(v.id)" :key="index">{{ v.title }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSave" :loading="editLoading">保存</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--激活表单-->
    <el-dialog title="激活" v-model="dialogFormVisible2" center width="400">
      <el-form ref="form" label-width="80px">
        <el-form-item label="激活">
          <el-switch v-model="batchStatus"></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleStatusBatchEdit" :loading="editLoading">确定</el-button>
          <el-button @click="dialogFormVisible2 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </section>
</template>
<script setup>
  import { ref } from "vue";
  import { ElMessage,ElMessageBox } from 'element-plus'
  import func from '@/common/func'
  const criteria = ref({
    username: '',
  })
  const tableData = ref([])
  const dialogFormVisible = ref(false)
  const dialogTitle = ref('')
  const editLoading = ref(false)
  const formRef = ref(null)
  const form = ref({
    id: 0,
    username: '',
    nickname: '',
    password: '',
    auth_ids: [],
  })
  const rules = ref({
    username: [
      {required: true, message: '请输入登录账户', trigger: 'blur'},
    ],
  })
  const authList = ref([])
  const batchStatus = ref(true)
  const dialogFormVisible2 = ref(false)
  const page = ref(1)
  const pageSize = ref(20)
  const totalCount = ref(0)
  let criteria_default = {}
  let ids = []
  let listUrl = '/system/adminList'
  let editUrl = '/system/adminEdit'
  let deleteUrl = '/system/adminDel'
  let setStatusUrl = '/system/adminEditStatus'

  for (let i in criteria.value) {
    if (criteria_default[i] === undefined) {
      criteria_default[i] = criteria.value[i];
    }
  }
  loadData();

  function onSubmit() {
    if (page.value !== 1) {
      page.value = 1;
    }
    loadData();
  }
  function onReset() {
    for (var i in criteria.value) {
      criteria.value[i] = criteria_default[i];
    }
  }
  function onpenStatusBatchEdit() {
    if (ids.length === 0) {
      ElMessage({message:'请选择要操作的数据',type: 'error'})
      return
    }
    batchStatus.value = true
    dialogFormVisible2.value = true
  }
  function handleStatusBatchEdit() {
    editLoading.value = true;
    func.request(setStatusUrl, {id: ids.join(','), status: batchStatus.value ? 1 : 0}).then(res => {
      editLoading.value = false;
      if (res.code === 1) {
        loadData();
        dialogFormVisible2.value = false
      }
    });
  }
  function changeStatus(status, index, row) {
    func.request(setStatusUrl, {id: row.id, status: status ? 1 : 0}).then(res => {
      if (res.code === 1) {
        row.status = status
        tableData.value[index] = row
      }
    });
  }
  function handleDelete(row) {
    ElMessageBox.confirm('确认删除吗？', '提示').then(() => {
      func.request(deleteUrl, {id: row.id}).then(res => {
        if (res.code === 1) {
          ElMessage({message: res.msg,type: 'success'})
          loadData()
        }
      });
    }).catch(()=>{})
  }
  function handleEdit(row) {
    if (row.id) {
      dialogTitle.value = '编辑'
      form.value = {
        id: row.id,
        username: row.username,
        password: '',
        nickname: row.nickname,
        auth_ids: row.auth_ids ? row.auth_ids.split(',') : [],
      }
    } else {
      dialogTitle.value = '添加'
      form.value = {
        id: 0,
        username: '',
        password: '',
        nickname: '',
        auth_ids: [],
      }
    }
    dialogFormVisible.value = true
  }
  function handleSave() {
    formRef.value.validate((valid) => {
      if (!valid) {
        return false
      }
      editLoading.value = true;
      func.request(editUrl, form.value).then(res => {
        editLoading.value = false;
        if (res.code === 1) {
          ElMessage({message: res.msg,type: 'success'})
          loadData()
          dialogFormVisible.value = false
        }
      });
    });
  }
  function handleCurrentChange(val) {
    if (page.value !== val) {
      page.value = val;
    }
    loadData();
  }
  function handleSizeChange(val) {
    if (pageSize.value !== val) {
      pageSize.value = val;
      loadData();
    }
  }
  function handleSelectionChange(v) {
    let r = []
    for (let item of v) {
      r.push(item.id)
    }
    ids = r
  }
  function loadData(is_export=false,all=false) {
    var pdt = {};
    if (undefined !== criteria.value) {
      pdt = JSON.parse(JSON.stringify(criteria.value));
    }
    pdt.page = page.value;
    pdt.pageSize = pageSize.value;
    if (is_export) {
      pdt.export = 1
      if (all) {
        pdt.page = 1;
        pdt.pageSize = 100000;
      } else {
        if (ids.length === 0) {
          ElMessage({message:'请选择要操作的数据',type: 'error'})
          return
        }
        pdt.ids = ids.join(',')
      }
    }
    func.request(listUrl, pdt).then(res => {
      if (res.code === 1) {
        if (is_export) {
          window.open(res.data.url)
          return
        }
        tableData.value = res.data.list;
        authList.value = res.data.authList;
        totalCount.value = res.data.total;
      }
    });
  }
</script>

<style lang="scss">

</style>
